#include "Subsystems/BlockBehaviors/SubsystemFertilizerBlockBehavior.h"
#include "Components/ComponentMiner.h"
#include "Blocks/SoilBlock.h"
#include "Blocks/SaltpeterChunkBlock.h"
#include "Subsystems/SubsystemTerrain.h"
#include "GameSingleton.h"


namespace PocketSurvival
{
    SubsystemFertilizerBlockBehavior::SubsystemFertilizerBlockBehavior()
    {
        m_handleBlocks.push_back(SaltpeterChunkBlock::Index());
    }

    bool SubsystemFertilizerBlockBehavior::onUse(const Ray3 &ray, ComponentMiner *componentMiner)
    {
        RaycastData raycastData = componentMiner->raycast(ray, RaycastMode::Digging);
        if (raycastData.terrainRaycastResult != nullptr && raycastData.terrainRaycastResult->cellFace.face == 4)
        {
            Point3 &cellFacePoint = raycastData.terrainRaycastResult->cellFace.point;
            int32_t y = cellFacePoint.posY;
            for (int32_t i = cellFacePoint.posX - 1; i <= cellFacePoint.posX + 1; i++)
            {
                for (int32_t j = cellFacePoint.posZ - 1; j <= cellFacePoint.posZ + 1; j++)
                {
                    int32_t cellValue = m_terrain->getCellValue(i, y, j);
                    if (Terrain::ExtractContents(cellValue) == SoilBlock::Index())
                    {
                        int32_t data = SoilBlock::SetNitrogen(Terrain::ExtractData(cellValue), 3);
                        int32_t value = Terrain::ReplaceData(cellValue, data);
                        m_terrain->changeCell(i, y, j, value);
                    }
                }
            }
            componentMiner->removeActiveTool(1);
            return true;
        }
        return false;
    }

    void SubsystemFertilizerBlockBehavior::load(const nlohmann::json &json)
    {
        m_terrain = GameSingleton::singletonPtr->getSingleton<SubsystemTerrain>();
    }

    static const std::string subsystemName = "FertilizerBlockBehavior";
    const std::string &SubsystemFertilizerBlockBehavior::getName() const
    {
        return subsystemName;
    }

}